﻿using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.XPath;


namespace EGIConsulting2.WebUI.YahooMap.v1.Util
{
    /// <summary>
    /// Readers a RSS 2.0 feed, this is a lightweight reader since we only
    /// want to parse the TTL element.
    /// </summary>
    public class RssReader
    {
        private string _response;
        private int _timeout = 3000;
        private bool _connected = false;
        private readonly HttpWebRequest _webRequest;

        public RssReader(string url) : this(url, "", "", "")
        {

        }
        public RssReader(string url, string proxyHost, string proxyUsername, string proxyPassword)
        {
            _webRequest = (HttpWebRequest)WebRequest.Create(url);

            //if we have proxy setup the webrequest
            if (proxyHost != string.Empty)
                _webRequest.Proxy = new WebProxy(proxyHost);

            //check if we need creditials for the proxy
            if (proxyUsername != string.Empty)
            {
                _webRequest.Proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword);
            }
        }

        /// <summary>
        /// Property to set the timeout in milliseconds
        /// we will wait before throwing a webexception
        /// </summary>
        public int TimeOut
        {
            get { return _timeout; }
            set { _timeout = value; }
        }

        /// <summary>
        /// Retrurns the repsonse from the Url
        /// </summary>
        /// <returns></returns>
        public string Response()
        {
            if (!_connected)
                Connect();

            return _response;
        }

        /// <summary>
        /// Returns the Time To Live value for the feed, if a feed doesn't have
        /// this value -1 will be returned
        /// </summary>
        /// <returns></returns>
        public int Ttl()
        {
            string ttl = GetElement("/rss/channel/ttl");
            if (ttl != null)
                return Int32.Parse(ttl);
            else
                return -1;

        }

        public string GetElement(string XpathQuery)
        {
            ArrayList list = GetElements(XpathQuery);
            if (list.Count > 0)
            {
                //just peel off the first item
                return list[0].ToString();
            }
            else
                return null;
        }

        public ArrayList GetElements(string XpathQuery)
        {
            if (!_connected)
                Connect();


            XmlTextReader reader = new XmlTextReader(_response, XmlNodeType.Document, null);
            XPathDocument doc = new XPathDocument(reader);
            XPathNavigator query = doc.CreateNavigator();
            XPathNodeIterator iterator = query.Select(XpathQuery);

            ArrayList elements = new ArrayList();

            while (iterator.MoveNext())
            {
                elements.Add(iterator.Current.Value);
            }

            reader.Close();
            return elements;

        }

        /// <summary>
        /// Connects to the remote Url and stores the response
        /// </summary>
        private void Connect()
        {
            _webRequest.Timeout = _timeout;
            WebResponse response = _webRequest.GetResponse();

            Stream input = response.GetResponseStream();
            StreamReader reader = new StreamReader(input);
            _response = reader.ReadToEnd();
            _connected = true;
        }
    }

}
